package com.neusoft.elmboot.controller;

import com.neusoft.elmboot.po.dto.UserDTO;
import com.neusoft.elmboot.service.BusinessService;
import com.neusoft.elmboot.util.CommonUtil;
import com.neusoft.elmboot.util.response.ResultBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.neusoft.elmboot.po.User;
import com.neusoft.elmboot.service.UserService;
import com.neusoft.elmboot.service.WalletService;

import java.util.Objects;

@RestController
@RequestMapping("/elm/UserController")
public class UserController {
	
	@Autowired
	private UserService userService;

	@Autowired
	private BusinessService businessService;

	@Autowired
	private BCryptPasswordEncoder encoder;

	@Autowired
	private WalletService walletService;

	@RequestMapping("/getUserByIdByPass")
	public User getUserByIdByPass(@RequestParam String userId,
								  @RequestParam String password) throws Exception{
		String encodedPwd = userService.getPasswordById(userId);
		if (BCrypt.checkpw(password, encodedPwd)) {
			User user1 = userService.getUserInfoById(userId);
			user1.setPassword("unknown");
			return user1;
		}
		return null;
	}

	@RequestMapping("/user/info")
	public ResultBody getUserInfoById(@RequestParam String userId) throws Exception{
		try {
			User user = userService.getUserInfoById(userId);
			if (user == null) {
				return ResultBody.error("获取失败！", null);
			}
			user.setPassword("unknown");
			return ResultBody.success("获取成功！", user);
		} catch (Exception e) {
			return ResultBody.error("获取失败！", null);
		}
	}
	
	@RequestMapping("/getUserById")
	public int getUserById(User user) throws Exception{
		return userService.getUserById(user.getUserId());
	}
	
	@RequestMapping("/saveUser")
	public int saveUser(User user) throws Exception{
		String userId = user.getUserId();
		if (userService.getUserById(userId) == 0) {
			// 保存原始密码用于创建支付密码
			String originalPassword = user.getPassword();
			user.setPassword(encoder.encode(originalPassword));
			int result = userService.saveUser(user);
			
			// 用户注册成功后，自动创建钱包
			if (result > 0) {
				try {
					// 使用用户登录密码的前6位作为初始支付密码（如果密码长度不足6位，则使用默认密码）
					String payPwd = originalPassword.length() >= 6 
						? originalPassword.substring(0, 6) 
						: "123456"; // 默认支付密码
					walletService.init(userId, payPwd);
				} catch (Exception e) {
					// 钱包创建失败不影响用户注册，只记录日志
					System.err.println("用户注册成功，但钱包创建失败: " + e.getMessage());
				}
			}
			
			return result;
		} else {
			return 0;
		}

	}

	@RequestMapping("/changePassword")
	public ResultBody changePassword(@RequestParam String userId,
									 @RequestParam String oldPassword,
									 @RequestParam String newPassword){
		try {
			String password = userService.getPasswordById(userId);
			if (!BCrypt.checkpw(oldPassword, password)) {
				return ResultBody.error("原始密码错误", null);
			}
			newPassword = encoder.encode(newPassword);
			userService.changePassword(userId, newPassword);
			return ResultBody.success("修改密码成功！", null);
		} catch (Exception e){
			return ResultBody.error("修改失败！", null);
		}
	}

	@RequestMapping("/user/updateInfo")
	public ResultBody updateInfo (@RequestParam String userId,
								  @RequestParam String userName,
								  @RequestParam String userImg) throws Exception {
		try {
			int userCnt = userService.getUserById(userId);
			if (userCnt == 0) {
				return ResultBody.error("不存在该用户！", null);
			}
			User user = userService.getUserInfoById(userId);
			UserDTO userDTO = new UserDTO(userId, userName, userImg);
			userService.updateInfo(userDTO);

			if (Objects.equals(user.getRole(), CommonUtil.ROLE_BUSINESS)) {
				businessService.updateBusinessById(userId, userName, userImg);
			}
			return ResultBody.success("修改成功！", null);
		} catch (Exception e) {
			return ResultBody.error("修改失败！", null);
		}
	}
}
